package io.github.yotta.common.web.advice;

import io.github.yotta.common.api.model.Response;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;

/**
 * @author yotta
 * @date 2025/3/12 17:06
 */
public class DefaultResponseWrapper implements ResponseWrapper<Response<?>>{

    @Override
    public Response<?> wrapperResponse(Object body, Class<?> type) {
        if (Objects.isNull(body)) {
            body = getDefaultValue(type);
        }
        // 方法不是Response类型的，就转为Response类型
        if (type != Response.class && type != ResponseEntity.class) {
            return Response.ok(body);
        } else {
            return (Response<?>) body;
        }
    }

    @Override
    public Response<?> wrapperErrorResponse(String msg, HttpStatus status, Exception ex) {
        return Response.fail(msg);
    }

    private Object getDefaultValue(Class returnType) {
        return Collection.class.isAssignableFrom(returnType) ? Collections.EMPTY_LIST : null;
    }
}
